package ctn.web.home.controller;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jmesa.core.filter.DateFilterMatcher;
import org.jmesa.core.filter.MatcherKey;
import org.jmesa.limit.Limit;
import org.jmesa.model.PageItems;
import org.jmesa.model.TableModel;
import org.jmesa.model.TableModelUtils;
import org.jmesa.view.component.Table;
import org.jmesa.view.editor.CellEditor;
import org.jmesa.view.editor.DateCellEditor;
import org.jmesa.view.html.HtmlBuilder;
import org.jmesa.view.html.component.HtmlColumn;
import org.jmesa.view.html.component.HtmlTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import ctn.contant.PlugContant;
import ctn.event.CTNEventCheckFun;
import ctn.event.CTNEventDropFun;
import ctn.event.CTNEventTransferFun;
import ctn.hibernate.po.CtnLinkEvent;
import ctn.hibernate.po.CtnUserMsgParm;
import ctn.service.dto.MyProjectDTO;
import ctn.service.inteface.PlugService;
import ctn.util.CPAUtil;
import ctn.util.CTNUserUtil;
import ctn.util.jmesa.DTOFilter;
import ctn.util.jmesa.DateUtils;
import ctn.util.jmesa.PageFilter;
import ctn.util.jmesa.PageSorter;
import ctn.util.jmesa.PaginationCriteria;
import ctn.util.jmesa.TableFacadeUtils;

@Controller
public class MyProjectController {
	@Autowired
	private PlugService plugServiceImpl;
	@Autowired
	private CPAUtil cpaUtil;
	@RequestMapping(value = "/main/pretransferfun")
	public ModelAndView pretransferfun(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv=new ModelAndView("myproject/transfer_fun");
		String funID=request.getParameter("id");
		MyProjectDTO dto=new MyProjectDTO();
		dto.setFunID(funID);
		mv.addObject("myProjectDTO",dto);
		return mv;
	}
	 @RequestMapping(value = "/main/transferfun")
		public ModelAndView transferfun(HttpServletRequest request,
				HttpServletResponse response,@ModelAttribute("myProjectDTO")MyProjectDTO myProjectDTO, BindingResult errors) throws Exception {
	    	ModelAndView mv=new ModelAndView("index/success");
	    	//生成邮件所需连接
	    	CTNEventTransferFun funEvent=new CTNEventTransferFun(myProjectDTO.getFunID(),myProjectDTO.getTranUserID());
	    	CtnLinkEvent event= cpaUtil.genEvent(funEvent);
	    	String link=cpaUtil.genLink(myProjectDTO.getTranUserID(), event);
	    	//创建邮件参数
	    	Set<CtnUserMsgParm> parms=new HashSet<CtnUserMsgParm>();
	    	parms.add(new CtnUserMsgParm("LN",link));
	    	parms.add(new CtnUserMsgParm("UR",CTNUserUtil.getUser().getName()));
	    	cpaUtil.genMsg(6L,Long.parseLong(myProjectDTO.getTranUserID()), parms);
	    	plugServiceImpl.doTransferFun(myProjectDTO);
	    	return mv;
	    }
	 @RequestMapping(value = "/main/dropfun")
		public ModelAndView dropfun(HttpServletRequest request,
				HttpServletResponse response) throws Exception {
	    	ModelAndView mv=new ModelAndView("index/success");
	    	//生成邮件所需连接
	    	String funID=request.getParameter("id");
	    	CTNEventDropFun dropEvent=new CTNEventDropFun(funID);
	    	//创建邮件参数
	    	Set<CtnUserMsgParm> parms=new HashSet<CtnUserMsgParm>();
	    	Long createUserID=plugServiceImpl.getCreateProjUserIDbyFunID(funID,parms);
	    	CtnLinkEvent event= cpaUtil.genEvent(dropEvent);
	    	String link=cpaUtil.genLink(String.valueOf(createUserID), event);
	    	
	    	parms.add(new CtnUserMsgParm("UR",CTNUserUtil.getUser().getName()));
	    	parms.add(new CtnUserMsgParm("DT",DateUtils.formatDateTime("yyyy-MM-dd HH:mm:ss", new Date())));
	    	parms.add(new CtnUserMsgParm("LN",link));
	    	
	    	cpaUtil.genMsg( 5L,createUserID, parms);
	    	plugServiceImpl.doDropFun(funID);
	    	return mv;
	    }
	 @RequestMapping(value = "/main/compfun")
		public ModelAndView compfun(HttpServletRequest request,
				HttpServletResponse response) throws Exception {
	    	ModelAndView mv=new ModelAndView("index/success");
	    	//生成邮件所需连接
	    	String funID=request.getParameter("id");
	    	CTNEventCheckFun dropEvent=new CTNEventCheckFun(funID);
	    	//创建邮件参数
	    	Set<CtnUserMsgParm> parms=new HashSet<CtnUserMsgParm>();
	    	Long createUserID=plugServiceImpl.getCreateProjUserIDbyFunID(funID,parms);
	    	CtnLinkEvent event= cpaUtil.genEvent(dropEvent);
	    	String link=cpaUtil.genLink(String.valueOf(createUserID), event);
	    	
	    	parms.add(new CtnUserMsgParm("UR",CTNUserUtil.getUser().getName()));
	    	parms.add(new CtnUserMsgParm("DT",DateUtils.formatDateTime("yyyy-MM-dd HH:mm:ss", new Date())));
	    	parms.add(new CtnUserMsgParm("LN",link));
	    	
	    	cpaUtil.genMsg( 4L,createUserID, parms);
	    	plugServiceImpl.doCheckFun(funID);
	    	return mv;
	    }
	 @RequestMapping(value="/main/listMyProject")
		public ModelAndView listMyProject(HttpServletRequest request,
				HttpServletResponse response) throws Exception{
			ModelAndView mv=new ModelAndView("myproject/myPorjShow");
			TableModel tableModel = new TableModel("listMyProject", request, response);
			tableModel.setStateAttr("restore");
			final PaginationCriteria criteria = new PaginationCriteria();
			tableModel.addFilterMatcher(new MatcherKey(Date.class, "createDate"), new DateFilterMatcher("yyyy-MM-dd"));
			tableModel.addFilterMatcher(new MatcherKey(Date.class, "planEndDate"), new DateFilterMatcher("yyyy-MM-dd"));
			tableModel.addFilterMatcher(new MatcherKey(Date.class, "endDate"), new DateFilterMatcher("yyyy-MM-dd"));
			tableModel.setItems(new PageItems() {

				@Override
				public int getTotalRows(Limit limit) {
					PageFilter pageFilter = TableFacadeUtils.getPageFilter(limit,
							MyProjectDTO.class);
					pageFilter.addFilter(new DTOFilter("userID",CTNUserUtil.getUser().getId()));
					criteria.setPageFilter(pageFilter);

					return plugServiceImpl.getListMyProjectCount(criteria).intValue();
				}

				@Override
				public List<MyProjectDTO> getItems(Limit limit) {
					PageSorter pageSorter = TableFacadeUtils.getPageSorter(limit);
					int rowStart = limit.getRowSelect().getRowStart();
					int rowEnd = limit.getRowSelect().getRowEnd();
					criteria.setPageSorter(pageSorter);
					criteria.setRowStart(rowStart);
					criteria.setRowEnd(rowEnd);
					return plugServiceImpl.getListMyProject(criteria);
				}
			});
		       tableModel.setTable(getHtmlTable());
			   String view = tableModel.render();
		        if (view == null) {
		            return null; // an export
		        } else {
		            // Setting a parameter to signal that this is an Ajax request.
		            String ajax = request.getParameter("ajax");
		            if (ajax != null && ajax.equals("true")) {
		                byte[] contents = view.getBytes();
		                response.getOutputStream().write(contents);
		                return null;
		            } else { // Not using Ajax if invoke the controller for the first time.
		                mv.addObject("wplughtml", view); // Set the Html in the request for the JSP.
		            }
		        }

		        return mv;
		}
	 private Table getHtmlTable() {
	        HtmlTable htmlTable  = TableModelUtils.createHtmlTable("proName","funName","createDate","funStatus","planEndDate","endDate","action");
	        htmlTable.setStyle("width:90%;");
	        htmlTable.setCaption("我开发中的项目");
	        htmlTable.getRow().getColumn("proName").setTitle("项目名称");
	        htmlTable.getRow().getColumn("proName").setWidth("15%");
	        htmlTable.getRow().getColumn("funName").setTitle("模块名称");
	        htmlTable.getRow().getColumn("funName").setWidth("15%");
	        htmlTable.getRow().getColumn("createDate").setTitle("创建时间");
	        htmlTable.getRow().getColumn("createDate").setWidth("15%");
	        htmlTable.getRow().getColumn("funStatus").setTitle("模块状态");
	        htmlTable.getRow().getColumn("funStatus").setWidth("10%");
	        htmlTable.getRow().getColumn("planEndDate").setTitle("计划结束时间");
	        htmlTable.getRow().getColumn("planEndDate").setWidth("15%");
	        htmlTable.getRow().getColumn("endDate").setTitle("结束时间");
	        htmlTable.getRow().getColumn("endDate").setWidth("15%");
	        htmlTable.getRow().getColumn("createDate").setCellEditor(new DateCellEditor("yyyy-MM-dd"));
	        htmlTable.getRow().getColumn("endDate").setCellEditor(new DateCellEditor("yyyy-MM-dd"));
	        htmlTable.getRow().getColumn("planEndDate").setCellEditor(new DateCellEditor("yyyy-MM-dd"));
	        HtmlColumn action=htmlTable.getRow().getColumn("action");
	        action.setTitle("操作");
	        action.setWidth("15%");
	        action.setFilterable(false);
	        action.setCellEditor(new CellEditor() {
				
				@Override
				public Object getValue(Object item, String property, int rowcount) {
					MyProjectDTO dto=(MyProjectDTO)item;
					HtmlBuilder html = new HtmlBuilder(); 
					if(!PlugContant.FUN_STATUS_COMPLETE.equals(dto.getFunStatus())&&!PlugContant.FUN_STATUS_END.equals(dto.getFunStatus())){
						if(!PlugContant.FUN_STATUS_WAIT_FOR_TRAN.equals(dto.getFunStatus())){
							html.ahref("${ctx}/main/pretransferfun?id="+dto.getFunID(), "转交").aEnd();
							html.nbsp();
						}
						if(!PlugContant.FUN_STATUS_WAIT_FOR_DROP.equals(dto.getFunStatus())){
							html.ahref("${ctx}/main/dropfun?id="+dto.getFunID(), "放弃").aEnd();
							html.nbsp();
						}
						if(!PlugContant.FUN_STATUS_WAIT_FOR_COMP.equals(dto.getFunStatus())){
							html.ahref("${ctx}/main/compfun?id="+dto.getFunID(), "完成").aEnd();
						}
					}
					return html.toString();
				}
			});
	        return htmlTable;
	    }
	 @RequestMapping(value="/main/listMyCreateProject")
		public ModelAndView listMyCreateProject(HttpServletRequest request,
				HttpServletResponse response) throws Exception{
			ModelAndView mv=new ModelAndView("myproject/myCPorjShow");
			TableModel tableModel = new TableModel("listMyCProject", request, response);
			tableModel.setStateAttr("restore");
			final PaginationCriteria criteria = new PaginationCriteria();
			tableModel.addFilterMatcher(new MatcherKey(Date.class, "createDate"), new DateFilterMatcher("yyyy-MM-dd"));
			tableModel.setItems(new PageItems() {

				@Override
				public int getTotalRows(Limit limit) {
					PageFilter pageFilter = TableFacadeUtils.getPageFilter(limit,
							MyProjectDTO.class);
					pageFilter.addFilter(new DTOFilter("userID",CTNUserUtil.getUser().getName()));
					criteria.setPageFilter(pageFilter);
					
					return plugServiceImpl.getListMyCreateProjectCount(criteria).intValue();
				}

				@Override
				public List<MyProjectDTO> getItems(Limit limit) {
					PageSorter pageSorter = TableFacadeUtils.getPageSorter(limit);
					int rowStart = limit.getRowSelect().getRowStart();
					int rowEnd = limit.getRowSelect().getRowEnd();
					criteria.setPageSorter(pageSorter);
					criteria.setRowStart(rowStart);
					criteria.setRowEnd(rowEnd);
					return plugServiceImpl.getListMyCreateProject(criteria);
				}
			});
		       tableModel.setTable(getHtmlTableForMyCreateProject());
			   String view = tableModel.render();
		        if (view == null) {
		            return null; // an export
		        } else {
		            // Setting a parameter to signal that this is an Ajax request.
		            String ajax = request.getParameter("ajax");
		            if (ajax != null && ajax.equals("true")) {
		                byte[] contents = view.getBytes();
		                response.getOutputStream().write(contents);
		                return null;
		            } else { // Not using Ajax if invoke the controller for the first time.
		                mv.addObject("wplughtml", view); // Set the Html in the request for the JSP.
		            }
		        }

		        return mv;
		}
	 private Table getHtmlTableForMyCreateProject() {
	        HtmlTable htmlTable  = TableModelUtils.createHtmlTable("proName","funStatus","createDate","ver","action");
	        htmlTable.setStyle("width:90%;");
	        htmlTable.setCaption("我创建的项目");
	        htmlTable.getRow().getColumn("proName").setTitle("项目名称");
	        htmlTable.getRow().getColumn("proName").setWidth("20%");
	        htmlTable.getRow().getColumn("funStatus").setTitle("项目状态");
	        htmlTable.getRow().getColumn("funStatus").setWidth("20%");
	        htmlTable.getRow().getColumn("createDate").setTitle("创建时间");
	        htmlTable.getRow().getColumn("createDate").setWidth("20%");
	        htmlTable.getRow().getColumn("ver").setTitle("当前版本");
	        htmlTable.getRow().getColumn("ver").setWidth("20%");
	        htmlTable.getRow().getColumn("createDate").setCellEditor(new DateCellEditor("yyyy-MM-dd"));
	        HtmlColumn action=htmlTable.getRow().getColumn("action");
	        action.setTitle("操作");
	        action.setWidth("20%");
	        action.setFilterable(false);
	        action.setCellEditor(new CellEditor() {
				
				@Override
				public Object getValue(Object item, String property, int rowcount) {
					MyProjectDTO dto=(MyProjectDTO)item;
					HtmlBuilder html = new HtmlBuilder(); 
					html.ahref("${ctx}/main/downspec?id="+dto.getFunID(), "删除").aEnd();
					html.nbsp();
					html.ahref("${ctx}/main/openspec?id="+dto.getFunID(), "编辑").aEnd();
					html.nbsp();
					html.ahref("${ctx}/main/openspec?id="+dto.getFunID(), "模块管理").aEnd();
					return html.toString();
				}
			});
	        return htmlTable;
	    }
}
